﻿using RimWorld;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;

namespace RimZombieGirl
{
    public class IncidentWorker_CurseSpread : IncidentWorker
    {
        protected override bool CanFireNowSub(IncidentParms parms)
        {
            Map map = (Map)parms.target;
            return map.mapPawns.FreeColonists.Any();
        }

        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map map = (Map)parms.target;
            List<Pawn> candidates = map.mapPawns.FreeColonists
                .Where(p => p.health != null && p.RaceProps.IsFlesh).ToList();

            if (!candidates.Any())
                return false;

            // 从 def 中读取配置
            IntRange fractionRange = def.GetModExtension<IncidentDefExtension_Curse>()?.victimRange ?? new IntRange(1, 1);
            //int maxVictims = def.GetModExtension<IncidentDefExtension_Curse>()?.maxVictims ?? 3;

            // 按照比例计算人数范围
            int numCandidates = candidates.Count;
            IntRange countRange = new IntRange(
                Mathf.RoundToInt(numCandidates * fractionRange.min),
                Mathf.RoundToInt(numCandidates * fractionRange.max)
            );

            int victimsCount = countRange.RandomInRange;
            victimsCount = Mathf.Clamp(victimsCount, 1, numCandidates);

            List<Pawn> victims = candidates.InRandomOrder().Take(victimsCount).ToList();

            foreach (Pawn pawn in victims)
            {
                HealthUtility.AdjustSeverity(pawn, ZombieDefOf.RI_CurseHediff, 0.02f);
            }

            string victimNames = string.Join(", ", victims.Select(p => p.LabelShortCap));
            string letterText = $"以下殖民者受到了神秘的诅咒：\n\n{victimNames}".Translate();

            SendStandardLetter(def.letterLabel, letterText, def.letterDef, parms, victims);
            return true;
        }
    }

    public class IncidentDefExtension_Curse : DefModExtension
    {
        public IntRange victimRange = new IntRange(1, 3); // 比例
        //public int maxVictims = 3; // 最大受害人数
    }
}
